package com.guit.hrms.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.guit.hrms.mapper.EmpResumeMapper;
import com.guit.hrms.mapper.QueryMapper;
import com.guit.hrms.po.Employee;
import com.guit.hrms.po.resume.EmployeeResume;
import com.guit.hrms.po.resume.EmployeeResumeFile;
import com.guit.hrms.po.resume.FieldPosition;
import com.guit.hrms.service.EmpResumeService;
import com.guit.hrms.utils.ExcelUtil;
import com.guit.hrms.utils.JsonUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Service
public class EmpResumeServiceImpl implements EmpResumeService {
    @Autowired
    private EmpResumeMapper empResumeMapper;
    @Autowired
    private QueryMapper queryMapper;

//    /**
//     * 根据员工工号获取员工履历
//     * @param employeeId 员工工号
//     * @return 员工履历
//     */
//    @Override
//    public EmployeeResumeFile findEmpResumeById(String employeeId) {
//        return empResumeMapper.findEmpResumeByEmpId(employeeId);
//    }

    /**
     * 根据员工工号更新员工履历
     * @param employeeResume 员工履历
     * @return 更新结果
     */
    @Override
    @Transactional
    public Integer updateEmpResume(EmployeeResume employeeResume) {
        EmployeeResumeFile employeeResumeFile = empResumeMapper.findEmpResumeByEmpId(employeeResume.getEmployeeId());
        if (employeeResumeFile == null) {
            return 0;
        }
        Map<String, FieldPosition> fieldPositionMap = JsonUtil.fromJson(employeeResumeFile.getFieldPositions(), new TypeReference<Map<String, FieldPosition>>() {});
        try {
            Workbook workbook = ExcelUtil.parseExcelFile(employeeResumeFile.getFileContent());
            Sheet sheet = workbook.getSheetAt(0);
            Row row = null;
            Cell cell = null;
//            if (employeeResume.getBasicInfo() != null){
//                FieldPosition namePosition = employeeResume.getBasicInfo().getName() == null ? null : fieldPositionMap.get("name");
//                FieldPosition genderPosition = employeeResume.getBasicInfo().getGender() == null ? null : fieldPositionMap.get("gender");
//                FieldPosition birthDatePosition = employeeResume.getBasicInfo().getBirthDate() == null ? null : fieldPositionMap.get("birthDate");
//                FieldPosition phonePosition = employeeResume.getBasicInfo().getPhone() == null ? null : fieldPositionMap.get("phone");
//                FieldPosition emailPosition = employeeResume.getBasicInfo().getEmail() == null ? null : fieldPositionMap.get("email");
//                if (namePosition != null) {
//                    row = sheet.getRow(namePosition.getRow());
//                    cell = row.getCell(namePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getName());
//                }
//                if (genderPosition != null) {
//                    row = sheet.getRow(genderPosition.getRow());
//                    cell = row.getCell(genderPosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getGender());
//                }
//                if (birthDatePosition != null) {
//                    row = sheet.getRow(birthDatePosition.getRow());
//                    cell = row.getCell(birthDatePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getBirthDate());
//                }
//                if (phonePosition != null) {
//                    row = sheet.getRow(phonePosition.getRow());
//                    cell = row.getCell(phonePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getPhone());
//                }
//                if (emailPosition != null) {
//                    row = sheet.getRow(emailPosition.getRow());
//                    cell = row.getCell(emailPosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getEmail());
//                }
//            }
//            if (employeeResume.getSelfEvaluation() != null){
//                FieldPosition position = fieldPositionMap.get("fieldContents[8]");
//                row = sheet.getRow(position.getRow());
//                cell = row.getCell(0);
//                cell.setCellValue(employeeResume.getSelfEvaluation());
//            }
            employeeResumeFile.setFileContent(ExcelUtil.saveWorkbookToBytes(workbook));
            employeeResumeFile.setUpdatedAt(LocalDateTime.now());
            return empResumeMapper.updateEmpResume(employeeResumeFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 在员工履历中添加记录
     * @param employeeResume 员工履历记录信息
     * @return 添加结果
     */
    @Override
    @Transactional
    public Integer addEmpResumeMsg(EmployeeResume employeeResume) {
        EmployeeResumeFile employeeResumeFile = empResumeMapper.findEmpResumeByEmpId(employeeResume.getEmployeeId());
        if (employeeResumeFile == null) {
            throw new RuntimeException("该员工没有履历信息");
        }
        Map<String, FieldPosition> fieldPositionMap = JsonUtil.fromJson(employeeResumeFile.getFieldPositions(), new TypeReference<Map<String, FieldPosition>>() {});
        String[] content = ExcelUtil.convertEmployeeResumeToFieldContents(employeeResume);
        try {
            Workbook workbook = ExcelUtil.parseExcelFile(employeeResumeFile.getFileContent());

            EmployeeResumeFile file = null;

            int i = fieldPositionMap.size() + 1;
            int insertRow = 0;
//            if (content.length != 0 && fieldPositionMap.get("fieldContents[" + i + "]") != null) {
//                System.out.println(Arrays.deepToString(content));
//                insertRow = fieldPositionMap.get("fieldContents[" + i + "]").getRow();
//                System.out.println(insertRow);
//            } else {
//                System.out.println("lastRow "+ workbook.getSheetAt(0).getLastRowNum());
                insertRow = workbook.getSheetAt(0).getLastRowNum()+1;
                System.out.println(insertRow);
//            }

//            for (int i = 0; i < content.length; i++) {
//                if (i == content.length){
//                    System.out.println(Arrays.toString(content));
//                    int insertRow = fieldPositionMap.get("fieldContents[" + i + "]").getRow();
//                    System.out.println(insertRow);
//                    file = ExcelUtil.insertRowIntoResumeExcel(workbook, fieldPositionMap, i, insertRow, content);
//                    employeeResumeFile.setFileContent(file.getFileContent());
//                    employeeResumeFile.setFieldPositions(file.getFieldPositions());
//                }
//            }
            file = ExcelUtil.insertRowIntoResumeExcel(workbook, fieldPositionMap, i, insertRow, content);
            employeeResumeFile.setFileContent(file.getFileContent());
            employeeResumeFile.setFieldPositions(file.getFieldPositions());

            workbook.close();
//            Sheet sheet = workbook.getSheetAt(0);
//            Row row = null;
//            Cell cell = null;
//            if (employeeResume.getBasicInfo() != null){
//                FieldPosition namePosition = employeeResume.getBasicInfo().getName() == null ? null : fieldPositionMap.get("name");
//                FieldPosition genderPosition = employeeResume.getBasicInfo().getGender() == null ? null : fieldPositionMap.get("gender");
//                FieldPosition birthDatePosition = employeeResume.getBasicInfo().getBirthDate() == null ? null : fieldPositionMap.get("birthDate");
//                FieldPosition phonePosition = employeeResume.getBasicInfo().getPhone() == null ? null : fieldPositionMap.get("phone");
//                FieldPosition emailPosition = employeeResume.getBasicInfo().getEmail() == null ? null : fieldPositionMap.get("email");
//                if (namePosition != null) {
//                    row = sheet.getRow(namePosition.getRow());
//                    cell = row.getCell(namePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getName());
//                }
//                if (genderPosition != null) {
//                    row = sheet.getRow(genderPosition.getRow());
//                    cell = row.getCell(genderPosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getGender());
//                }
//                if (birthDatePosition != null) {
//                    row = sheet.getRow(birthDatePosition.getRow());
//                    cell = row.getCell(birthDatePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getBirthDate());
//                }
//                if (phonePosition != null) {
//                    row = sheet.getRow(phonePosition.getRow());
//                    cell = row.getCell(phonePosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getPhone());
//                }
//                if (emailPosition != null) {
//                    row = sheet.getRow(emailPosition.getRow());
//                    cell = row.getCell(emailPosition.getCol());
//                    cell.setCellValue(employeeResume.getBasicInfo().getEmail());
//                }
//            }
//            if (employeeResume.getSelfEvaluation() != null){
//                FieldPosition position = fieldPositionMap.get("fieldContents[8]");
//                row = sheet.getRow(position.getRow());
//                cell = row.getCell(0);
//                cell.setCellValue(employeeResume.getSelfEvaluation());
//            }
//            employeeResumeFile.setFileContent(ExcelUtil.saveWorkbookToBytes(workbook));
            employeeResumeFile.setUpdatedAt(LocalDateTime.now());
            return empResumeMapper.updateEmpResume(employeeResumeFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出(下载)员工履历
     * @param employeeId 员工工号
     * @return 员工履历
     */
    @Override
    public EmployeeResumeFile downloadEmpResume(String employeeId) {
        return empResumeMapper.findEmpResumeByEmpId(employeeId);
    }

    /**
     * 导入员工履历
     * @param employeeResume 员工履历信息
     * @return 导入结果
     */
    @Override
    @Transactional
    public Integer importEmpResume(EmployeeResume employeeResume) {
        Employee employee = queryMapper.getById(employeeResume.getEmployeeId());
        if (employee == null){
            throw new RuntimeException("员工不存在");
        }
        EmployeeResumeFile employeeResumeFile0 = empResumeMapper.findEmpResumeByEmpId(employeeResume.getEmployeeId());
        try {
            EmployeeResumeFile employeeResumeFile = ExcelUtil.createResumeExcel(employeeResume);
            employeeResumeFile.setUpdatedAt(LocalDateTime.now());
            employeeResumeFile.setEmployeeId(employee.getEmployeeId());
            Integer result = 0;
            if (employeeResumeFile0 == null){
                employeeResumeFile.setEmployeeId(employeeResume.getEmployeeId());
                employeeResumeFile.setFileName(employeeResume.getEmployeeId()+employee.getUsername()+"的履历");
                result = empResumeMapper.createEmpResume(employeeResumeFile);
            } else {
                result = empResumeMapper.updateEmpResume(employeeResumeFile);
            }
            if (result == 0){
                throw new RuntimeException("员工履历导入失败");
            } else {
                return result;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
